﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System.Runtime.Serialization;
using System;
using System.ComponentModel;
using System.Threading;

namespace BrainTechLLC.ThreadSafeObjects
{
    /// <summary>
    /// ThreadSafeCounter provides a counter that can be safely accessed and changed from multiple threads
    /// </summary>
    [Serializable]
    [DataContract]
    public class ThreadSafeCounterLong
    {
        public override string ToString()
        {
            return _count.ToString();
        }

        [DataMember]
        private long _count;
        public long Count { get { return _count; } }

        public void ZeroCounter()
        {
            SetCounter(0);
        }

        public void SetCounter(long count)
        {
            Interlocked.Exchange(ref _count, count);
        }

        public void Add(long num)
        {
            Interlocked.Add(ref _count, num);
        }

        public long Increment()
        {
            return Interlocked.Increment(ref _count);
        }

        public static ThreadSafeCounterLong operator ++(ThreadSafeCounterLong counter)
        {
            long n = Interlocked.Increment(ref counter._count);
            return counter;
        }

        public static ThreadSafeCounterLong operator --(ThreadSafeCounterLong counter)
        {
            long n = Interlocked.Decrement(ref counter._count);
            return counter;
        }

        public static ThreadSafeCounterLong operator +(ThreadSafeCounterLong counter, long add)
        {
            long n = Interlocked.Add(ref counter._count, add);
            return counter;
        }

        public static ThreadSafeCounterLong operator -(ThreadSafeCounterLong counter, long subtract)
        {
            long n = Interlocked.Add(ref counter._count, -subtract);
            return counter;
        }

        public static implicit operator long(ThreadSafeCounterLong counter) { return counter.Count; }
    }
}
